<template>
  <div class="journal-part-4">
    <div class="content">
      <div class="header-title">
        <div class="part-title">Part IV - {{ $t("btnText.task.part_4") }}</div>
        <div class="right-btn" @click="onClickAddPartFour">
          <IconPlus></IconPlus>
          <span>{{ $t("btnText.add") }}</span>
        </div>
      </div>
      <template v-for="(item, index) in partFourData" :key="item.id">
        <div class="header-title" v-if="index != 0">
          <div class="part-title"></div>
          <div class="right-btn delete" @click="onDeletePartFour(item.id)">
            <span>{{ $t("btnText.delete") }}</span>
          </div>
        </div>
        <div class="part-form" v-if="partFourData && partFourData.length > 0">
          <a-form label-align="left">
            <div class="row">
              <div class="col">
                <a-form-item :label="$t('form.task.part_4_form.item_1.label')">
                  <a-input
                    @blur="onPartFourBlur(item, index)"
                    v-model:value="item.employer"
                  ></a-input>
                  <div class="tips">
                    {{ $t("form.task.part_4_form.item_1.tip") }}
                  </div>
                </a-form-item>
              </div>
              <div class="tips">
                {{ $t("form.task.part_4_form.item_1.tip") }}
              </div>
              <div class="col">
                <a-form-item :label="$t('form.task.part_4_form.item_2.label')">
                  <a-input
                    @blur="onPartFourBlur(item, index)"
                    v-model:value="item.address"
                  ></a-input>
                  <div class="tips">
                    {{ $t("form.task.part_4_form.item_2.tip") }}
                  </div>
                </a-form-item>
              </div>
              <div class="tips">
                {{ $t("form.task.part_4_form.item_2.tip") }}
              </div>
            </div>
            <div class="row">
              <div class="col">
                <a-form-item :label="$t('form.task.part_4_form.item_3.label')">
                  <a-input
                    @blur="onPartFourBlur(item, index)"
                    v-model:value="item.occupation"
                  ></a-input>
                  <div class="tips" style="visibility: hidden">###</div>
                </a-form-item>
              </div>
              <div class="col">
                <a-form-item :label="$t('form.task.part_4_form.item_4.label')">
                  <a-input
                    @blur="onPartFourBlur(item, index)"
                    v-model:value="item.validator"
                  ></a-input>
                  <div class="tips">
                    {{ $t("form.task.part_4_form.item_4.tip") }}
                  </div>
                </a-form-item>
              </div>
              <div class="tips">
                {{ $t("form.task.part_4_form.item_4.tip") }}
              </div>
            </div>
            <div class="row">
              <div class="col">
                <a-form-item :label="$t('form.task.part_4_form.item_7.label')">
                  <a-date-picker
                    @change="onPartFourChange(item)"
                    v-model:value="item.start_time"
                  ></a-date-picker>
                  <div class="tips">
                    {{ $t("form.task.part_4_form.item_7.tip") }}
                  </div>
                </a-form-item>
              </div>
              <div class="col">
                <a-form-item :label="$t('form.task.part_4_form.item_8.label')">
                  <a-date-picker
                    @change="onPartFourChange(item)"
                    v-model:value="item.end_time"
                  ></a-date-picker>
                  <div class="tips">
                    {{ $t("form.task.part_4_form.item_8.tip") }}
                  </div>
                </a-form-item>
              </div>
            </div>
          </a-form>
        </div>
        <div
          class="divider-line"
          v-if="index !== partFourData.length - 1"
        ></div>
      </template>
      <div class="divider-line"></div>
      <div class="header-title">
        <div class="part-title">Part IV - {{ $t("btnText.task.part_4") }}</div>
        <div class="right-btn" @click="onClickAddPartFour2">
          <IconPlus></IconPlus>
          <span>{{ $t("btnText.add") }}</span>
        </div>
      </div>
      <template v-for="(item, index) in partFour2Data" :key="item.id">
        <div class="header-title" v-if="index != 0">
          <div class="part-title"></div>
          <div class="right-btn delete" @click="onDeletePartFour2(item.id)">
            <span>{{ $t("btnText.delete") }}</span>
          </div>
        </div>
        <div class="part-form">
          <a-form label-align="left">
            <div class="row">
              <div class="col">
                <a-form-item :label="$t('form.task.part_4_form.item_5.label')">
                  <a-textarea
                    :maxlength="1000"
                    v-model:value.trim="item.aircraft_owner"
                    @blur="onPartFour2Blur(item, index)"
                    :autoSize="areaRows"
                  ></a-textarea>
                  <div class="tips">
                    {{ $t("form.task.part_4_form.item_5.tip") }}
                  </div>
                </a-form-item>
              </div>
              <div class="tips">
                {{ $t("form.task.part_4_form.item_5.tip") }}
              </div>
              <div class="col">
                <a-form-item :label="$t('form.task.part_4_form.item_6.label')">
                  <a-textarea
                    :maxlength="1000"
                    v-model:value.trim="item.work_nature"
                    @blur="onPartFour2Blur(item, index)"
                    :autoSize="areaRows"
                  ></a-textarea>
                  <div class="tips" style="visibility: hidden">####</div>
                </a-form-item>
              </div>
            </div>
            <div class="row">
              <div class="col">
                <a-form-item :label="$t('form.task.part_4_form.item_7.label')">
                  <a-date-picker
                    @change="onPartFour2Change(item)"
                    v-model:value="item.start_time"
                  ></a-date-picker>
                  <div class="tips">
                    {{ $t("form.task.part_4_form.item_7.tip") }}
                  </div>
                </a-form-item>
              </div>
              <div class="col">
                <a-form-item :label="$t('form.task.part_4_form.item_8.label')">
                  <a-date-picker
                    @change="onPartFour2Change(item)"
                    v-model:value="item.end_time"
                  ></a-date-picker>
                  <div class="tips">
                    {{ $t("form.task.part_4_form.item_8.tip") }}
                  </div>
                </a-form-item>
              </div>
            </div>
          </a-form>
        </div>
        <div
          class="divider-line"
          v-if="index !== partFour2Data.length - 1"
        ></div>
      </template>
    </div>
    <div class="footer-btn">
      <a-button @click="goto('/member/journal', { step: 3 })">{{
        $t("btnText.prev_step")
      }}</a-button>
      <a-button type="primary" @click="goto('/member/journal', { step: 5 })">{{
        $t("btnText.next_step")
      }}</a-button>
    </div>
  </div>
</template>

<script setup lang="ts">
import { getCurrentInstance, ref } from "vue";
import {
  postPartFourAll,
  postPartFourUpdate,
  postPartFourCreate,
  postPartFourDelete,
  postPartFour2All,
  postPartFour2Update,
  postPartFour2Create,
  postPartFour2Delete,
} from "../../../../api/part";
import { Modal } from "ant-design-vue";
import type { PartFour, PartFour2 } from "../../../../types/part";
import dayjs from "dayjs";
import { useMemberStore } from "../../../../store";
import { RegDateYYYYMMDD } from "../../../../data/reg";

const memberStore = useMemberStore();

const $t = getCurrentInstance()?.appContext.config.globalProperties.$t;
// ===========================Part One =================================================================
let partFourCacheData: PartFour[] = [
  {
    address: "",
    employer: "",
    end_time: "",
    start_time: "",
    occupation: "",
    validator: "",
  },
];
const setPartFourCacheData = () => {
  partFourCacheData = JSON.parse(JSON.stringify(partFourData.value));
};
const partFourData = ref<PartFour[]>();
const getPartFourData = async () => {
  let res = await postPartFourAll();
  if (res.code === 200) {
    if (res.data) {
      partFourData.value = res.data;
      partFourData.value!.map((item) => {
        item.start_time && RegDateYYYYMMDD.test(item.start_time)
          ? (item.start_time = formatDate(item.start_time))
          : (item.start_time = "");
        item.end_time && RegDateYYYYMMDD.test(item.end_time)
          ? (item.end_time = formatDate(item.end_time))
          : (item.end_time = "");
      });
      partFourData.value!.reverse();
      setPartFourCacheData();
    }
  }
};

// 添加part4-1信息
const onClickAddPartFour = async () => {
  let params: PartFour = {
    employer: "",
    address: "",
    end_time: "",
    start_time: "",
    occupation: "",
    validator: "",
  };
  let res = await postPartFourCreate(params);
  if (res.code === 200) {
    getPartFourData();
  }
};

// 删除 Part4-1
const onDeletePartFour = (id: number) => {
  Modal.confirm({
    title: $t("dialog.delete_data.title"),
    content: $t("dialog.delete_data.desc"),
    okText: $t("btnText.ensure"),
    cancelText: $t("btnText.cancel1"),
    maskClosable: true,
    async onOk() {
      let res = await postPartFourDelete(id);
      if (res.code === 200) {
        getPartFourData();
      }
    },
    onCancel() {},
  });
};

// 判断表单是否变化
const checkPartFourChanged = (item: PartFour, index: number) => {
  let flag = false;
  let cacheData = partFourCacheData[index];
  if (cacheData.address != item.address) flag = true;
  if (cacheData.employer != item.employer) flag = true;
  if (cacheData.occupation != item.occupation) flag = true;
  if (cacheData.validator != item.validator) flag = true;
  return flag;
};

// 文本框失焦
const onPartFourBlur = (item: PartFour, index: number) => {
  if (checkPartFourChanged(item, index)) {
    updatePartFourData(item);
  }
};

// 日期选择器改变
const onPartFourChange = (item: PartFour) => {
  updatePartFourData(item);
};

// 向后端发送请求更新数据
const updatePartFourData = async (data: PartFour) => {
  let obj = {
    start_time: dayjs(data.start_time).format("YYYY-MM-DD"),
    end_time: dayjs(data.end_time).format("YYYY-MM-DD"),
    member_id: memberStore.profile?.id,
  };
  let params = JSON.parse(JSON.stringify(data));
  Object.assign(params, obj);
  let res = await postPartFourUpdate(params);
  if (res.code === 200) {
    setPartFourCacheData();
  }
};

// ===========================Part Two ===============================
let partFour2CacheData: PartFour2[] = [
  {
    aircraft_owner: "",
    work_nature: "",
    start_time: "",
    end_time: "",
  },
];
const setPartFour2CacheData = () => {
  partFour2CacheData = JSON.parse(JSON.stringify(partFour2Data.value));
};
const partFour2Data = ref<PartFour2[]>();
const getPartFour2Data = async () => {
  let res = await postPartFour2All();
  if (res.code === 200) {
    res.data ? (partFour2Data.value = res.data) : null;
    partFour2Data.value!.map((item) => {
      item.start_time && RegDateYYYYMMDD.test(item.start_time)
        ? (item.start_time = formatDate(item.start_time))
        : (item.start_time = "");
      item.end_time && RegDateYYYYMMDD.test(item.end_time)
        ? (item.end_time = formatDate(item.end_time))
        : (item.end_time = "");
    });
    partFour2Data.value!.reverse();
    setPartFour2CacheData();
  }
};

// 添加part4-2信息
const onClickAddPartFour2 = async () => {
  let params: PartFour2 = {
    aircraft_owner: "",
    work_nature: "",
    start_time: "",
    end_time: "",
  };
  let res = await postPartFour2Create(params);
  if (res.code === 200) {
    getPartFour2Data();
  }
};

// 删除 Part4-2
const onDeletePartFour2 = (id: number) => {
  Modal.confirm({
    title: "确认删除",
    content: "此操作将永久删除该数据",
    okText: "确定",
    cancelText: "取消",
    maskClosable: true,
    async onOk() {
      let res = await postPartFour2Delete(id);
      if (res.code === 200) {
        getPartFour2Data();
      }
    },
    onCancel() {},
  });
};

// 判断表单是否变化
const checkPartFour2Changed = (item: PartFour2, index: number) => {
  let flag = false;
  let cacheData = partFour2CacheData[index];
  if (cacheData.aircraft_owner != item.aircraft_owner) flag = true;
  if (cacheData.work_nature != item.work_nature) flag = true;
  return flag;
};

// 文本框失焦
const onPartFour2Blur = (item: PartFour2, index: number) => {
  if (checkPartFour2Changed(item, index)) {
    updatePartFour2Data(item);
  }
};

// 日期选择器改变
const onPartFour2Change = (item: PartFour2) => {
  updatePartFour2Data(item);
};

// 向后端发送请求更新数据
const updatePartFour2Data = async (data: PartFour2) => {
  let obj = {
    start_time: dayjs(data.start_time).format("YYYY-MM-DD"),
    end_time: dayjs(data.end_time).format("YYYY-MM-DD"),
    member_id: memberStore.profile?.id,
  };
  let params = JSON.parse(JSON.stringify(data));
  Object.assign(params, obj);
  let res = await postPartFour2Update(params);
  if (res.code === 200) {
    setPartFour2CacheData();
  }
};

// =========================样式================================
const areaRows = ref({ minRows: 2, maxRows: 2 });
const resetAreaRows = () => {
  if (isMobile()) {
    areaRows.value.minRows = 1;
    areaRows.value.maxRows = 1;
  } else {
    areaRows.value.minRows = 2;
    areaRows.value.maxRows = 2;
  }
};

onMounted(() => {
  resetAreaRows();
  getPartFourData();
  getPartFour2Data();
  window.addEventListener("resize", resetAreaRows);
});
</script>
<style scoped lang="less">
@import url("./common.less");
.journal-part-4 {
  padding-right: 720px;
}
.header-title {
  .part-title {
    margin-bottom: 0;
  }
  margin-bottom: 24px;
}

@media screen and (max-width: 768px) {
  .journal-part-4 {
    padding-right: 0;
    padding: 123px;
    border-radius: 82px;
    border: 1px solid #ccd6de;
  }
  .divider-line {
    display: none;
  }
}
</style>
